#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/09/14 09:54:18
'''
import sys
sys.path.append('.')

from models.medicament_models import EntityStockRecord
from db_logic.medicament import BllMedicament
from db_logic.db_base import Repository
from Common.Utils import Utils
import json


class BllStockRecord(Repository):

    def __init__(self, entityType=EntityStockRecord):
        return super().__init__(entityType)
    

    def get_list_info(self, page_param, client_id, func_type):
        filter_base = ""
        if client_id:
            filter_base += f" client_id='{client_id}' "
        if func_type:
            if filter_base:
                filter_base += " and "
            filter_base += f"func_type={func_type}"
        if filter_base:
            filter_base = f" where {filter_base} "
        
        sql_all = f"""
            SELECT a.*, client_name FROM (
                select * from `rms_stock_record` {filter_base}
            ) a LEFT JOIN(
                select client_name, client_id from rms_client
            ) b on a.client_id=b.client_id
            order by create_date desc
        """
        try:
            # count_number = len(self.execute(sql_all).fetchall())
            count_number = self.execute(f"select count(*) num from rms_stock_record {filter_base} ").fetchone().num
        except:
            count_number = 0
        page_param.totalRecords = count_number
        page_sql = Utils.sql_paging_assemble(sql_all, page_param)
        return self.execute(page_sql).fetchall()
    
    def set_stock_info(self, client_id, client_code, user_info, func_type, medicament_info):
        # 查询当前在库试剂信息
        try:
            obj = EntityStockRecord(
                client_id=client_id,
                client_code=client_code,
                func_type=func_type,
                create_date=Utils.get_str_datetime(),
                medicament_info=json.dumps(medicament_info),
                user_id=user_info.user_id,
                user_name=user_info.real_name
            )
            self.insert(obj)
            return True
        except Exception as error:
            return error

    def inster_test_stock(self):
        data_list = []
        for i in range(4, 101):
            obj = EntityStockRecord(
                client_id='1c39cb24-07f8-11ed-abd4-f47b094925e1',
                client_code=6,
                func_type=1,
                create_date=Utils.get_str_datetime(),
                medicament_info='',
                user_id='4cea74ee-0d8b-11ed-943e-f47b094925e1',
                user_name=i
            )
            data_list.append(obj)
        self.insert_many(data_list)

if __name__ == '__main__':
    BllStockRecord().inster_test_stock()



        

